package com.xdqzy.baseline.common.service.impl;

import com.xdqzy.baseline.common.config.FileServerProperties;
import com.xdqzy.baseline.common.exception.BusinessException;
import com.xdqzy.baseline.common.exception.CtbcAssert;
import com.xdqzy.baseline.common.service.FileServerService;
import com.xdqzy.baseline.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.joda.time.DateTime;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;

/**
 * @author : winter
 * @version V1.0
 * @Title: 本地文件服务器
 * @ClassName : com.ctbc.backend.common.service.impl.LocalFileServerService.java
 * @Description :
 * @date :  2020-11-03 22:47
 */
@Slf4j
public class LocalFileServerService implements FileServerService {

    private String targetPath;

    private String prefix;

    public LocalFileServerService(FileServerProperties.LocalFileServerProperties fileServerProperties) {
        Assert.hasText(fileServerProperties.getLocalPrefix(), "本地文件服务器前缀错误");
        Assert.hasText(fileServerProperties.getTargetPath(), "本地文件服务器目标地址错误");
        File dir = new File(fileServerProperties.getTargetPath());
        if (!dir.exists() || !dir.isDirectory()) {
            boolean mkdirs = dir.mkdirs();
            Assert.isTrue(mkdirs, "创建文件夹失败");
        }
        this.prefix = fileServerProperties.getLocalPrefix();
        this.targetPath = fileServerProperties.getTargetPath();
        log.info("本地服务器上传目录:{},前缀:{}", fileServerProperties.getTargetPath(), fileServerProperties.getLocalPrefix());
    }

    @Override
    public String uploadFile(MultipartFile file) {
        try (InputStream stream = file.getInputStream()) {
            File targetDir = new File(targetPath, DateTime.now().toString(DateUtils.DAY_FORMAT));
            if (!targetDir.exists()) {
                boolean mkdirs = targetDir.mkdirs();
                CtbcAssert.isTrue(mkdirs, "创建文件夹失败");
            }
            String fileName = DateTime.now().toString(DateUtils.MILL_SECOND_FORMAT) + "-" + RandomStringUtils.randomNumeric(3) + getFileType(file);
            FileUtils.copyToFile(stream, new File(targetDir, fileName));
            return prefix + targetDir.getName() + "/" + fileName;
        } catch (Exception e) {
            log.error("上传文件失败", e);
            throw new BusinessException(1, "文件上传失败");
        }
    }
}
